package com.mp.ipm2020.common.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Auther adidasshe@mp.cn
 * <p>
 * 消息接收缓存件
 */
@Component
public class CacheUtil {
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 开启异步任务将收到的mqtt订阅消息写入redis缓存队列中
     *
     * @param topic 如果topic为"ipmPub"则存入ipmPub list队列缓存起来待接口模块存入mysql
     * @param data  具体的设备数据信息
     */
    @Async
    public void add(String topic, String data) {
//      将数据压入redis List队列的头部
        if ("ipmPub".equalsIgnoreCase(topic)) {
            redisUtil.lSetLeft(topic, data);
            System.out.println("收到数据" + new Date() + redisUtil.lGetIndex(topic, 0));
        }
    }

    /**
     * 获取缓存中的"ipmPub"队列数据，从尾部开始消费存入mysql数据库中
     *
     * @param topic ipmPub
     */
    public String get(String topic) {
        long size = redisUtil.lGetListSize(topic);
        if (size != 0) {
            String data = (String) redisUtil.lGetIndex(topic, -1);
//            System.out.println(data);
            return data;
        }
        return null;
    }


}
